<template>
  <div class="empty-space"></div>
  <div class="carousel-container">
    <el-carousel :interval="5000" type="card" height="380px" arrow="never">
      <el-carousel-item v-for="(item, index) in carouselItems" :key="index" wir>
        <router-link :to="getTargetLink(index)" class="product-link">
          <img
            class="carousel-image"
            :src="item.imageUrl"
            :alt="item.altText"
            style="cursor: pointer"
          />
        </router-link>
      </el-carousel-item>
    </el-carousel>
  </div>
  <div class="main">
    <div class="back-button" v-if="showBackButton">
      <el-button @click="cancel" circle class="return"
        ><el-icon>
          <ArrowLeft /> </el-icon
      ></el-button>
    </div>
    <div class="zoom-controls">
      <el-button circle @click="zoomIn" class="add"
        ><el-icon>
          <Plus /> </el-icon
      ></el-button>
      <el-button circle @click="zoomOut" class="minus"
        ><el-icon>
          <Minus /> </el-icon
      ></el-button>
    </div>
    <!-- 多余诗人放这 -->
    <div><br /><br /><br /></div>
    <div class="floating-button-noclear">
      <el-tooltip
        content="点击此处查看地址不详诗人"
        placement="top"
        effect="light"
      >
        <el-button
          @click="showPoetsWithUnknownCities"
          v-if="!unknownCitiesPoetsVisibility"
          >查看地址不详诗人<el-icon>
            <Collection /> </el-icon
        ></el-button>
      </el-tooltip>
    </div>

    <div class="floating-button">
      <el-tooltip
        content="点击此处查看本省家乡不详诗人"
        placement="top"
        effect="light"
      >
        <el-button
          @click="showPoetsWithUnknownCities"
          v-if="unknownCitiesPoetsVisibility"
          >查看更多诗人<el-icon>
            <Collection /> </el-icon
        ></el-button>
      </el-tooltip>
    </div>
    <div class="map-frame">
      <div class="map-container">
        <div class="box" ref="areaRankingAll"></div>
      </div>
    </div>
    <div v-if="!showPoetDistributionMap">
      <el-tooltip
        content="点击此处查看诗人分布图"
        placement="top"
        effect="light"
      >
        <el-button style="margin-bottom: 40px" @click="showPoetDistribution"
          >查看诗人分布图<el-icon>
            <Location /> </el-icon
        ></el-button>
      </el-tooltip>
    </div>
    <div v-if="showPoetDistributionMap">
      <el-button style="margin-bottom: 40px" @click="showPoetDistribution"
        >关闭诗人分布图<el-icon>
          <Location /> </el-icon
      ></el-button>
    </div>
    <div class="map-frame-distribution" v-if="showPoetDistributionMap">
      <div class="map-container-distribution">
        <img src="@/assets/诗人地区分布图.png" alt="诗人分布图" />
      </div>
    </div>
  </div>

  <div>
    <el-drawer v-model="ifDrawerOpen" :direction="direction">
      <template #header>
        <h2 class="drawerCity">{{ cityName }}</h2>
      </template>
      <template #default>
        <div>
          <el-divider
            ><span class="divider-text">生于斯长于斯</span></el-divider
          >
        </div>
        <div class="drawer-content">
          <div
            v-if="poetNum === 0 && Loading === false"
            class="no-poet-message"
          >
            抱歉，暂无诗人收录。
          </div>
          <el-collapse
            v-loading="Loading"
            v-model="activeNames"
            @change="handleChange"
          >
            <!-- 使用 v-for 指令遍历诗人数组 -->
            <el-collapse-item
              v-for="(poet, index) in poetData"
              :key="index"
              :title="poet.name"
              :name="index"
            >
              <div>
                <img v-if="poet.image" :src="poet.image" :alt="poet.name" />
                <!-- 根据诗人的编号生成详情页链接 -->
                <router-link
                  :to="`/PoetDetails/${poet.id}`"
                  class="product-link"
                >
                  <h2>{{ poet.name }}</h2>
                </router-link>
                <p>{{ poet.summary }}</p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <el-backtop :target="'.drawer-content'" :right="100" :bottom="100" />
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-row
            ><el-col :span="6">
              <el-statistic title="诗人数量" :value="poetNum" />
            </el-col>
            <el-col :span="12">
              <router-link
                class="link"
                :to="{ path: '/Poet', query: { location_id: locate_id } }"
                >查看此地全部诗人➩</router-link
              >
            </el-col>
          </el-row>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import axios from "axios";
import "@/assets/font/font.css"; //引入字体
import { ElMessageBox, Popover } from "element-plus";
import { defineComponent, ref } from "vue";
var echarts = require("echarts");

export default defineComponent({
  name: "areaRankingAll",
  data() {
    return {
      myChart: null,
      publicUrl: "https://geo.datav.aliyun.com/areas_v3/bound/",
      allCode: [],
      showBackButton: false,
      initialWidth: 0,
      initialHeight: 0,
      isPopoverVisible: false,
      cityName: "",
      ifDrawerOpen: false,
      unknownCitiesPoetsVisibility: false,
      isNullPoet: false, // 是否正在获取家乡不详的诗人
      poet: {
        name: "诗人的名字",
        avatar: "诗人的头像链接",
        bio: "诗人的个人简介",
        num: 1,
      },
      poetNum: 0,
      poetData: {}, // 用于存储从后端获取的诗人数据
      locate_id: null,
      province_id: null,
      activeNames: ["1"],
      carouselItems: [
        // 走马灯
        { imageUrl: require("@/assets/image1.jpg"), altText: "Image 1" },
        { imageUrl: require("@/assets/image2.jpg"), altText: "Image 2" },
        { imageUrl: require("@/assets/image3.jpg"), altText: "Image 3" },
      ],
      showPoetDistributionMap: false,
      calculate_page_flag: true,
      Loading: false,
    };
  },
  mounted() {
    //生命周期钩子
    this.initChart();

    // 发送axios请求获取诗人数据
    // this.fetchPoetData();
    this.calculate_page();
  },
  components: {
    Popover,
  },
  methods: {
    //返回中国地图
    cancel() {
      this.initChart();
    },

    // 放大地图
    zoomIn() {
      this.adjustMapSize(1.2); // 增加20%的大小
    },

    //缩小地图
    zoomOut() {
      this.adjustMapSize(0.8); // 减少20%的大小
    },

    // 调整地图大小
    adjustMapSize(scale) {
      let areaRankingAll = this.$refs.areaRankingAll;

      // 如果初始大小尚未记录，则记录初始大小
      if (this.initialWidth === 0 && this.initialHeight === 0) {
        this.initialWidth = areaRankingAll.offsetWidth;
        this.initialHeight = areaRankingAll.offsetHeight;
      }

      let newWidth = areaRankingAll.offsetWidth * scale;
      let newHeight = areaRankingAll.offsetHeight * scale;

      //如果倍数为一，代表恢复初始大小
      if (scale !== 1) {
        // 计算新的大小
        newWidth = areaRankingAll.offsetWidth * scale;
        newHeight = areaRankingAll.offsetHeight * scale;
      } else if (scale == 1) {
        newWidth = this.initialWidth;
        newHeight = this.initialHeight;
      }

      // 调整地图容器大小
      areaRankingAll.style.width = `${newWidth}px`;
      areaRankingAll.style.height = `${newHeight}px`;

      // 重新绘制图表
      this.myChart.resize();
    },

    getGeoJson(jsonName) {
      //拼接url获取对应
      return axios.get(this.publicUrl + jsonName);
    },
    initEcharts(geoJson, name, chart, parentName) {
      let self = this;
      echarts.registerMap(name, geoJson); //注册可用的地图
      let titleText = parentName ? parentName + ">" + name : name;
      let option = {
        // 图表的配置项
        title: {
          text: titleText,
          left: "center", // 标题居中显示
        },
        series: [
          {
            type: "map",
            map: name,
            label: {
              fontSize: 14, // 调整字体大小
              color: "#c7cbbc",
              fontWeight: "bold",
            },
            data: [],
            itemStyle: {
              normal: {
                // 默认状态下的地图区域颜色
                areaColor: "#9c3622",
                // 边框颜色
                borderColor: "#e4ab79",
                // 边框宽度
                borderWidth: 1,
              },
              emphasis: {
                show: true,
                areaColor: "#2a5aaf", //鼠标选中区域颜色
                label: {
                  show: true,
                  textStyle: {
                    color: "#c7cbbc",
                  },
                },
              },
            },
          },
        ],
      };

      chart.setOption(option); //将配置项设置给echarts实例对象
      chart.off("click"); //移除点击事件
      chart.on("click", (params) => {
        //直辖市 不下钻
        let specialCodes = {
          110000: true,
          120000: true,
          310000: true,
          500000: true,
          710000: true,
          810000: true,
          820000: true,
        };

        //地级市 .json
        let cityCodes = {
          419001: true,
          429004: true,
          429005: true,
          429006: true,
          429021: true,
          469001: true,
          469002: true,
          469005: true,
          469006: true,
          469007: true,
          469021: true,
          469022: true,
          469023: true,
          469024: true,
          469025: true,
          469026: true,
          469027: true,
          469028: true,
          469029: true,
          469030: true,
          659002: true,
          659003: true,
          659004: true,
          659005: true,
          659006: true,
          659007: true,
          659008: true,
          659010: true,
        };

        let clickCode = String(
          self.allCode.filter((areaJson) => areaJson.name === params.name)[0]
            .adcode
        ); //从用户点击的地区名字返回行政编码
        self.locate_id = clickCode;
        if (!this.province_id) {
          this.province_id = clickCode;
        }
        console.log("打印clickCode", clickCode);
        console.log("打印province_id", this.province_id);
        this.cityName = params.name;
        if (!specialCodes[clickCode]) {
          this.unknownCitiesPoetsVisibility = true;
        }

        if (
          (clickCode.slice(-4) !== "0000" && clickCode.slice(-2) === "00") ||
          cityCodes[clickCode]
        ) {
          //判断点击的地区，市级不再进行下钻
          //后续添加诗人网页
          this.ifDrawerOpen = true;
          this.fetchPoetData();
          return;
        }

        // 北京重庆上海天津澳门香港 已经大地图 不再下钻
        if (titleText.includes(">")) {
          if (specialCodes[clickCode]) {
            this.ifDrawerOpen = true;
            this.fetchPoetData();
            return;
          }
        }
        //北京重庆上海天津澳门香港及地级市 不显示子区域 用.json
        if (specialCodes[clickCode] || cityCodes[clickCode]) {
          clickCode = clickCode + ".json"; //.json只显示自己
        } else clickCode = clickCode + "_full.json"; //_full.json显示自己和孩子

        //获取地区相应的json 传递构建新的地图
        self
          .getGeoJson(clickCode)
          .then((res) => {
            self.showBackButton = true; // 显示返回按钮
            self.initEcharts(res.data, params.name, chart, titleText);
          })
          .catch((err) => {
            console.log(err, "err");
            self.getGeoJson("100000_full.json").then((China) => {
              self.showBackButton = false; // 不显示返回按钮
              self.initEcharts(China.data, "中华人民共和国", chart);
            });
          });
      });
      this.myChart = chart; // 保存图表实例以便后续操作
      this.adjustMapSize(1); // 在初始化时将地图大小恢复到初始大小
    },
    //地图初始化
    initChart() {
      let chart = echarts.init(this.$refs.areaRankingAll);
      this.getGeoJson("all.json").then((all) => {
        this.allCode = all.data; //获取所有的区域编码信息
      });
      this.getGeoJson("100000_full.json").then((China) => {
        this.showBackButton = false; // 初始化时不显示返回按钮
        this.initEcharts(China.data, "中华人民共和国", chart);
      });
      this.unknownCitiesPoetsVisibility = false;
      this.province_id = null;
    },
    handleChange(val) {
      console.log(val);
    },
    fetchPoetData() {
      // const locate_id = this.isNullPoet ? 0 : this.locate_id;
      const locate_id = this.locate_id;
      console.log("打印取得此地locate_id:", locate_id); // 打印 locate_id 的值
      this.Loading = true; //设置缓冲图案
      axios
        .post("location/" + Number(locate_id) + "/" + 1, {
          page: 0,
          perPage: 0,
        })
        .then((response) => {
          this.Loading = false; //关闭缓冲图案
          this.poetData = response.data;
        })
        .catch((error) => {
          console.error("错了:", error);
        });

      axios
        .get("location/" + Number(locate_id))
        .then((response) => {
          this.poetNum = response.data.poetry_num;
        })
        .catch((error) => {
          console.error("GET request error:", error);
        });
    },
    //获取家乡不详的诗人信息
    showPoetsWithUnknownCities() {
      this.cityName = "未知城市";
      if (!this.province_id) {
        this.locate_id = "0";
      } else {
        this.locate_id = this.province_id; // 设置标志位为 true
      }
      this.ifDrawerOpen = true;
      this.fetchPoetData(); // 获取诗人信息
    },

    getTargetLink(index) {
      // 根据索引返回相应的链接
      if (index === 0) {
        return "/PoetDetails/31";
      } else if (index === 1) {
        return "/PoetDetails/28";
      } else if (index === 2) {
        return "/PoetDetails/5";
      } else {
        // 如果有更多的图片，可以继续添加条件
        // 或者返回一个默认链接
        return "/nonono";
      }
    },
    showPoetDistribution() {
      this.showPoetDistributionMap = !this.showPoetDistributionMap;
    },
    calculate_page() {
      if (this.calculate_page_flag) {
        axios
          .get("calculate_poetry")

          .catch((error) => {
            console.error("trytry", error);
          });
      }
    },
  },
});
</script>

<style scoped>
/*主体 */
.main {
  height: auto;
  background-color: #f0f2ec;
}

/*地图 */
.map-frame {
  position: relative;
  margin: 0 auto;
  margin-bottom: 25px;
  width: 1080px;
  height: 750px;
  border: 5px solid #ccc;
  background-color: #ffffff;
  padding-top: 80px;
  /* 添加内部上边距 */
}

.map-frame-distribution {
  position: relative;
  margin: 0 auto;
  margin-bottom: 100px;
  width: 1080px;
  height: 635px;
  border: 5px solid #ccc;
  background-color: #ffffff;
  padding-top: 20px;
  /* 添加内部上边距 */
}

.map-container {
  position: relative;
  height: 750px;
  /* 设置地图容器的初始高度 */
  overflow: auto;
  /* 显示地图容器溢出部分的滚动条 */
}

.map-container-distribution {
  position: relative;
  height: 635px;
  /* 设置地图容器的初始高度 */
  overflow: auto;
  /* 显示地图容器溢出部分的滚动条 */
}

.box {
  width: 100%;
  height: 100%;
}

/*控制按钮 */
.add,
.minus {
  color: #e2dbd0;
  background-color: #7f8885;
}

.return {
  color: #f2efe5;
  background-color: #a1a690;
}

.back-button,
.zoom-controls {
  position: absolute;
  top: 550px;
}

.floating-button {
  top: 1350px;
  position: absolute;
  left: 9%;
  z-index: 5;
}

.floating-button-noclear {
  top: 1350px;
  position: absolute;
  left: 7%;
  z-index: 5;
}

.floating-button-picture {
  top: 1300px;
  position: absolute;
  left: 9%;
  z-index: 5;
}

.float {
  color: #edf2e9;
  background-color: #86a8a5;
}

.back-button {
  left: 10%;
}

.zoom-controls {
  right: 10%;
}

/*空白条 */
.empty-space {
  height: 20px;
}

/*走马灯 */
.carousel-container {
  margin-top: 20px;
  margin-bottom: 100px;
  height: 380px;
  position: relative;
  overflow: hidden;
}

.carousel-image {
  height: auto;
  max-height: 100%;
  object-fit: contain;
}

/*抽屉 */
.drawerCity {
  font-family: STZhongSong;
  font-size: 26px;
  color: #333;
}
.divider-text {
  font-family: KaiTi;
  font-size: 18px;
  letter-spacing: 1px;
  /* 间距 */
  /* 其他样式 */
}
.link {
  width: auto;
}

.drawer-content {
  overflow: auto;
  height: 100%;
}

.no-poet-message {
  color: #888;
  font-size: 18px;
  font-style: italic;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>